import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
// import ReportFormMachineAlarmStatistics from '@main/entities/service/admin/reportForm/report-form-period-status-monitoring.entity';
import {
  Repository,
  // IsNull, Between, In
} from 'typeorm';
// import { SysOperationLogService } from '../../system/operationLog/operationLog.service';
import BaseMachine from '@main/entities/service/admin/base/base-machine.entity';

@Injectable()
export class ReportFormMachineAlarmStatisticsService {
  constructor(
    @InjectRepository(BaseMachine)
    private machineRepository: Repository<BaseMachine>
  ) {}

  /**
   * 罗列所有配置
   */
  async list(data) {
    const { entity = {} } = data;

    const { machineCodeList, dateStartTime, dateEndTime } = entity;

    const machineCodes = machineCodeList.length
      ? `IN ('${machineCodeList.join("','")}')`
      : 'IS NOT NULL';

    const sql = `
      SELECT
        DATE(a.create_time) AS date,
        d.machine_code AS machineCode,
        d.machine_name AS machineName,
        COUNT( a.id ) AS count,
        SUM( CASE WHEN a.alarm_type_code = '1' THEN 1 ELSE 0 END ) AS alarmType1Count,
        SUM( CASE WHEN a.alarm_type_code = '2' THEN 1 ELSE 0 END ) AS alarmType2Count
        FROM
          base_machine d
        LEFT JOIN wip_alarm_record a ON d.machine_code = a.machine_code AND DATE(a.create_time) BETWEEN '${dateStartTime}' AND '${dateEndTime}'
        WHERE
            d.machine_code ${machineCodes}
        GROUP BY
          d.machine_code,
          DATE(a.create_time)
        ORDER BY
          DATE(a.create_time)
      `;

    const result = await this.machineRepository.query(sql);

    const resultMap = new Map<string, any>();

    // 创建日期范围内的所有日期
    const currentDate = new Date(dateStartTime);
    const end = new Date(dateEndTime);

    while (currentDate <= end) {
      const dateStr = currentDate.toISOString().split('T')[0]; // 格式化为 YYYY-MM-DD
      resultMap.set(dateStr, { date: dateStr, data: [] });
      currentDate.setDate(currentDate.getDate() + 1);
    }

    // 收集所有的设备信息
    const machineMap = new Map<string, string>(); // 机器代码与机器名称的映射
    result.forEach((row) => {
      if (row.machineCode && row.machineName) {
        machineMap.set(row.machineCode, row.machineName);
      }
    });

    // 初始化每个日期的设备信息，统计条数为 0
    const machineList = Array.from(machineMap.keys());
    machineList.forEach((machineCode) => {
      const machineName = machineMap.get(machineCode) || ''; // 获取机器名称
      resultMap.forEach((dateEntry) => {
        dateEntry.data.push({
          machineCode,
          machineName,
          count: 0, // 初始化计数为 0
          alarmVos: [
            {
              machineCode,
              machineName,
              alarmType: '1',
              count: 0,
              sumDate: dateEntry.date,
            },
            {
              machineCode,
              machineName,
              alarmType: '2',
              count: 0,
              sumDate: dateEntry.date,
            },
          ],
        });
      });
    });

    // 遍历数据并填充到对应的日期对象中
    result.forEach((row) => {
      const { date, machineCode, count, alarmType1Count, alarmType2Count } = row;

      const dateEntry = resultMap.get(date);
      if (dateEntry) {
        // 查找对应的设备条目
        const machineEntry = dateEntry.data.find((m) => m.machineCode === machineCode);
        if (machineEntry) {
          // 更新计数
          machineEntry.count += count || 0;
          machineEntry.alarmVos[0].count += alarmType1Count || 0;
          machineEntry.alarmVos[1].count += alarmType2Count || 0;
        }
      }
    });

    // 将结果转换为数组
    return Array.from(resultMap.values());

    // const list = result.reduce((acc, row) => {
    //   let dateEntry = acc.find((entry) => entry.date === row.date);
    //   if (!dateEntry) {
    //     dateEntry = { date: row.date, data: [] };
    //     acc.push(dateEntry);
    //   }

    //   let machineEntry = dateEntry.data.find((m) => m.machineCode === row.machineCode);
    //   if (!machineEntry) {
    //     machineEntry = {
    //       machineCode: row.machineCode,
    //       machineName: row.machineName,
    //       count: row.count || 0, // 确保数量为 0
    //       alarmVos: [
    //         {
    //           machineCode: row.machineCode,
    //           machineName: row.machineName,
    //           alarmType: '1',
    //           count: row.alarmType1Count || 0,
    //           sumDate: row.date,
    //         },
    //         {
    //           machineCode: row.machineCode,
    //           machineName: row.machineName,
    //           alarmType: '2',
    //           count: row.alarmType2Count || 0,
    //           sumDate: row.date,
    //         },
    //       ],
    //     };
    //     dateEntry.data.push(machineEntry);
    //   }

    //   return acc;
    // }, []);

    // // console.log(result);

    // return list;

    // return this.formatResult(result);
  }
}
